package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Resource
    CacheClient cacheClient;

    @Override
    public Result queryById(Long id) {
        // 缓存穿透
        // Shop shop = queryWithPassThrough(id);
        // 缓存击穿 互斥锁
        // Shop shop = queryWithMutex(id);
        // 缓存击穿 逻辑过期
        // Shop shop = queryWithLogicExpire(id);

        // 封装缓存穿透
        // Shop shop = cacheClient.queryWithPassThrough(RedisConstants.CACHE_SHOP_KEY, id, Shop.class, this::getById, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        // 封装逻辑过期
        Shop shop = cacheClient.queryWithLogicExpire(RedisConstants.CACHE_SHOP_KEY, id, Shop.class, this::getById, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);

        if (shop == null) {
            return Result.fail("店铺不存在！");
        }
        return Result.ok(shop);
    }

    // 创建线程池
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    private Shop queryWithLogicExpire(Long id) {
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        // 不存在 直接返回null
        if (StrUtil.isBlank(shopJson)) {
            return null;
        }
        // 获取数据
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        // 判断是否过期 如果是当前时间之后，说明没过期 直接返回数据
        if (expireTime.isAfter(LocalDateTime.now())) {
            return shop;
        }

        // 已过期 缓存重建 获取互斥锁
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        boolean lock = tryLock(lockKey);
        // 成功获取到互斥锁，开启新线程进行缓存重建逻辑
        if (lock) {
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    this.saveShop2Redis(id, 10L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unLock(lockKey);
                }
            });
        }

        // 返回过期的数据
        return shop;
    }

    public void saveShop2Redis(Long id, Long expireSeconds) {
        // 模拟复杂业务执行时间，才能测试出建立完成缓存之前返回了过期数据
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        Shop shop = getById(id);
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        // 设置逻辑过期时间
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    private Shop queryWithMutex(Long id){
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        // 从redis查询商户缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        // 判断缓存是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            // 存在 直接返回
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        // 判断是否空值
        if (shopJson != null) {
            return null;
        }
        Shop shop = null;
        try {
            // 到这里说明缓存不存在
            // 实现缓存重建
            String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
            boolean lock = tryLock(lockKey);
            // 判断是否成功获取互斥锁 没拿到说明已经有线程拿到互斥锁 正在进行缓存重建 则经过一定时间后重试
            if (!lock) {
                Thread.sleep(50);
                return queryWithMutex(id);
            }

            // -- 进行DoubleCheck 到这里说明拿到了互斥锁 进行二次检查缓存是否存在，存在则无需建立缓存
            // 从redis查询商户缓存
            shopJson = stringRedisTemplate.opsForValue().get(key);
            // 判断缓存是否存在
            if (StrUtil.isNotBlank(shopJson)) {
                // 存在 直接返回
                return JSONUtil.toBean(shopJson, Shop.class);
            }

            // 执行业务逻辑 进行缓存重建
            shop = getById(id);
            // 不存在 为避免触发缓存穿透 存空对象2分钟
            if(shop == null) {
                stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, "" , RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            // 存在 写入redis
            stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
            // 解除互斥锁
            unLock(lockKey);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        return shop;
    }
    // 上互斥锁
    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        // 使用工具类对Boolean进行判断， 防止自动拆箱导致Boolean出现null
        return BooleanUtil.isTrue(flag);
    }
    // 解锁
    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }


    private Shop queryWithPassThrough(Long id) {
        String s = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
        Shop shop = null;
        // 空串 说明redis中没有 mysql中也没有的数据
        if ("".equals(s)) {
            return null;
        }
        // value是空说明不存在缓存，则查询并新增缓存，设置过期时间
        if (s == null) {
            shop = getById(id);
            // 得到的对象是空，说明redis中没有，mysql也没有，出现缓存穿透，通过设置TTL为2min的空串解决
            if (shop == null) {
                stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            } else {
                // 对象不是空 则正常设置缓存 设置返回的对象
                stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
                shop = JSONUtil.toBean(s, Shop.class);
            }
        }
        return shop;
    }

    @Override
    @Transactional // 先更新数据库 再删除缓存 使用事务确保一致性
    public Result update(Shop shop) {
        updateById(shop);
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + shop.getId());
        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        // 没有传入经纬度数据，则直接返回数据
        if(x == null || y == null) {
            Page<Shop> page = query().eq("type_id", typeId).page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            return Result.ok(page.getRecords());
        }

        // 计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;

        String key = RedisConstants.SHOP_GEO_KEY + typeId;
        // 得到经纬度附近半径5km的商户
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().search(
                key,
                GeoReference.fromCoordinate(x, y),
                new Distance(5000), // 5km
                RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeCoordinates().limit(end)
        );
        // 没有查到
        if (results == null) {
            return Result.ok(Collections.emptyList());
        }
        // 得到符合范围条件的商户id
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        // 当前总数据条数比起始数据位置小，说明没有新的数据了
        if (list.size() <= from) {
            return Result.ok(Collections.emptyList());
        }

        ArrayList<Long> ids = new ArrayList<>(list.size());
        HashMap<String, Distance> distanceMap = new HashMap<>(list.size());
        // skip能使得从from下标开始处理，前面的数据跳过
        list.stream().skip(from).forEach(result -> {
            // 保存店铺id
            String shopIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            Distance distance = result.getDistance();
            // 保存店铺id和GEO信息
            distanceMap.put(shopIdStr, distance);
        });
        // 根据id批量查询商户数据，并按传入顺序返回数据
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("order by field(id," + idStr + ")").list();
        // 得到的距离数据分别放入每个商户数据中
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        return Result.ok(shops);
    }
}
